<?php


namespace app\model;


use think\facade\Db;
use think\response\Json;
use \Exception as E;

class QrcodeModel
{
    private static $_table = 'eb_qrcode'; // 配送箱编号表

    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [2]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [
                ['operate_id', '=', $adminInfo['id']],
                ['school_id', '=', $input['school_id']]
            ];
            $field = 'id,code,status, FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time';
            $table = Db::table(self::$_table)
                ->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $list]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加
     * @param $input
     * @param $token
     * @return Json
     */
    public static function add($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [2]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $date = new \DateTime();
            $code = $date->format('YmdHisu');
            $whereSql = Db::table(self::$_table)->field('id')->where('code', $code)->fetchSql(true)->find();
            $where = "not exists ({$whereSql})";
            $input['code'] = $code;
            $input['operate_id'] = $adminInfo['id'];
            $input['status'] = 0;
            $input['create_time'] = time();
            $sql = makeDualSql(self::$_table, $input, $where);
            $rtn = Db::table(self::$_table)->execute($sql);
            if ($rtn) return jsonSuccess('添加成功');
            return jsonFail('添加失败，请重试');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**删除
     * @param $input
     * @param $token
     * @return Json
     */
    public static function delete($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [2]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [
                ['id', '=', $input['id']],
                ['school_id', '=', $input['school_id']],
                ['operate_id', '=', $adminInfo['id']]
            ];
            $rtn = Db::table(self::$_table)->where($map)->delete();
            if ($rtn) return jsonSuccess('删除成功');
            return jsonFail('删除失败，请刷新页面重试');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }
}